package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.MapUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.ShippingAddressStatusEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.entity.UserShippingAddress;
import com.frogs.ucenter.service.UserShippingAddressService;

@Service("userShippingAddressService")
public class UserShippingAddressServiceImpl extends UserBaseServiceImpl implements UserShippingAddressService {

	private static Logger log = LoggerFactory.getLogger(UserShippingAddressServiceImpl.class);
	
	
	@Override
	public JSONObject updateUserAddress(Integer userId, UserShippingAddress userShippingAddress)  throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_ADDRESS_UPDATE");
		
		String[] otherParams = {ApiUrlParamEnum.province.getParamName(),StringUtil.isEmpty(userShippingAddress.getProvince()) ? 
										"" : userShippingAddress.getProvince(),
								ApiUrlParamEnum.city.getParamName(),StringUtil.isEmpty(userShippingAddress.getCity()) ? 
										"" : userShippingAddress.getCity(),
								ApiUrlParamEnum.district.getParamName(),StringUtil.isEmpty(userShippingAddress.getDistrict()) ? 
										"" : userShippingAddress.getDistrict(),
								ApiUrlParamEnum.street.getParamName(),StringUtil.isEmpty(userShippingAddress.getStreet()) ?
										"" : userShippingAddress.getStreet(),
								ApiUrlParamEnum.contacts.getParamName(), userShippingAddress.getContacts(),
								ApiUrlParamEnum.contactNumber.getParamName(),StringUtil.isEmpty(userShippingAddress.getContactNumber()) ?
										"" : userShippingAddress.getContactNumber() ,
								ApiUrlParamEnum.postcode.getParamName(),userShippingAddress.getPostcode(),
								ApiUrlParamEnum.isDefault.getParamName(),StringUtil.isEmpty(userShippingAddress.getIsDefault()) ? 
										"0" : userShippingAddress.getIsDefault().toString(),
								ApiUrlParamEnum.isPrivacy.getParamName(),StringUtil.isEmpty(userShippingAddress.getIsPrivacyReceipt()) ? 
										"0" : userShippingAddress.getIsPrivacyReceipt().toString(),
								ApiUrlParamEnum.isTemporaryAddress.getParamName(),StringUtil.isEmpty(userShippingAddress.getIsTemporaryAddress()) ? 
										"0" : userShippingAddress.getIsTemporaryAddress().toString(),
								ApiUrlParamEnum.rank.getParamName(),StringUtil.isEmpty(userShippingAddress.getRank()) ? 
										"0" : userShippingAddress.getRank().toString(),
								ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								ApiUrlParamEnum.areaCode.getParamName(),userShippingAddress.getAreaId(),
								ApiUrlParamEnum.telNumber.getParamName(),StringUtil.isEmpty(userShippingAddress.getTelNumber()) ?
										"" : userShippingAddress.getTelNumber(),
								ApiUrlParamEnum.name.getParamName(),StringUtil.isEmpty(userShippingAddress.getName()) ?
										"" : userShippingAddress.getName(),
								ApiUrlParamEnum.userShippingAddressId.getParamName(),null == userShippingAddress.getId() ?
										"0" : userShippingAddress.getId().toString(),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[updateUserAddress] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("修改用户地址接口异常！");
		}
		return result;
	}
	
	public JSONObject updateUserAddressByMap(Map<String,Object> addressMap) throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_ADDRESS_UPDATE");
		String[] otherParams = MapUtil.convertToStringArray(addressMap);
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[updateUserAddressByMap] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), allParams , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("修改用户地址接口异常！");
		}
		return result;
	}
	@Override
	public JSONObject addUserAddress(Integer userId, UserShippingAddress userShippingAddress) throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_ADDRESS_ADD");
		
		String[] otherParams = {ApiUrlParamEnum.province.getParamName(),StringUtil.isEmpty(userShippingAddress.getProvince()) ? 
						"" : userShippingAddress.getProvince(),
				ApiUrlParamEnum.city.getParamName(),StringUtil.isEmpty(userShippingAddress.getCity()) ? 
						"" : userShippingAddress.getCity(),
				ApiUrlParamEnum.district.getParamName(),StringUtil.isEmpty(userShippingAddress.getDistrict()) ? 
						"" : userShippingAddress.getDistrict(),
				ApiUrlParamEnum.street.getParamName(),StringUtil.isEmpty(userShippingAddress.getStreet()) ?
						"" : userShippingAddress.getStreet(),
				ApiUrlParamEnum.contacts.getParamName(), StringUtil.isEmpty(userShippingAddress.getContacts()) ?
						"" : userShippingAddress.getContacts(),
				ApiUrlParamEnum.contactNumber.getParamName(),StringUtil.isEmpty(userShippingAddress.getContactNumber()) ?
						"" : userShippingAddress.getContactNumber(),
				ApiUrlParamEnum.postcode.getParamName(),StringUtil.isEmpty(userShippingAddress.getPostcode()) ? 
						"" : userShippingAddress.getPostcode(),
				ApiUrlParamEnum.isDefault.getParamName(),null == userShippingAddress.getIsDefault() ? "0":userShippingAddress.getIsDefault().toString(),
				ApiUrlParamEnum.isPrivacy.getParamName(),null == userShippingAddress.getIsPrivacyReceipt() ? "0" : userShippingAddress.getIsPrivacyReceipt().toString(),
				ApiUrlParamEnum.isTemporaryAddress.getParamName(),null == userShippingAddress.getIsTemporaryAddress() ? "0" : userShippingAddress.getIsTemporaryAddress().toString(),
				ApiUrlParamEnum.rank.getParamName(),null == userShippingAddress.getRank() ? "0" : userShippingAddress.getRank().toString(),
				ApiUrlParamEnum.userId.getParamName(),userId.toString(),
				ApiUrlParamEnum.areaCode.getParamName(),StringUtil.isEmpty(userShippingAddress.getAreaId()) ? 
						"" : userShippingAddress.getAreaId(),
				ApiUrlParamEnum.telNumber.getParamName(),StringUtil.isEmpty(userShippingAddress.getTelNumber()) ?
						"" : userShippingAddress.getTelNumber(),
				ApiUrlParamEnum.name.getParamName(),StringUtil.isEmpty(userShippingAddress.getName()) ? 
						"" : userShippingAddress.getName(),
				};
		
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[addUserAddress] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("新增用户地址接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject showUserAddress(Integer userId, Integer userAddressId) throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_ADDRESS_SHOW");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.userShippingAddressId.getParamName(), userAddressId.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[showUserAddress] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("显示用户地址接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject deleteUserAddress(Integer userId, Integer userAddressId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_ADDRESS_DELETE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								ApiUrlParamEnum.userShippingAddressId.getParamName(),userAddressId.toString(),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[deleteUserAddress] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("删除用户地址接口异常！");
		}
		return result;
	}

	@Override
	public List<UserShippingAddress> getUserAddressListForList(Integer pageNo,
			Integer pageSize, Integer userId) throws Exception {
		try {
			JSONObject jsonObj = getUserAddressList(pageNo, pageSize, userId);
			JSONArray jsr = jsonObj.getJSONObject("response").getJSONArray("list");
			List<UserShippingAddress> addressList = new ArrayList<UserShippingAddress>();
			if (jsr != null) {
				addressList = JSONObject.parseArray(jsr.toJSONString(), UserShippingAddress.class);
			}
			return addressList;
		} catch(IllegalStateException e) {
			log.error("func[getUserAddressListForList]  pageNo[{}] pageSize[{}] userId[{}] exception[{} - {}] desc[fail]",
					new Object[] { pageNo, pageSize ,userId,e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			return new ArrayList<UserShippingAddress>();
		}catch(Exception e){
			throw new Exception("获取用户地址接口异常！");
		}
	}
	
	@Override
	public JSONObject mergeUserDefaultAddress(Integer userId, Integer addressId, String areaId, String province, String city, String district,String phone) throws Exception {
		UserShippingAddress address = new UserShippingAddress();
		if(addressId > 0) {
			JSONObject json = showUserAddress(userId, addressId);
			if(null != json.getJSONObject("response") && null != json.getJSONObject("response").getJSONObject("info")) {
				address = JSONObject.toJavaObject(json.getJSONObject("response").getJSONObject("info"), UserShippingAddress.class);
			}
		}
		address.setProvince(province);
		address.setCity(city);
		address.setDistrict(district);
		address.setId(addressId);
		address.setUserId(userId);
		address.setAreaId(areaId);
		address.setIsDefault(ShippingAddressStatusEnum.STATUS_DEFAULT.getId());
		if(!StringUtil.isEmpty(phone)) {
			address.setContactNumber(phone);
		}
		if(addressId <= 0) {
			//添加用户默认地址
			return addUserAddress(userId, address);
		} else {
			//修改默认用户地址
			return updateUserAddress(userId, address);
		}
	}

	@Override
	public JSONObject defaultUserAddress(Integer userId, Integer userAddressId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_ADDRESS_DEFAULT");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								ApiUrlParamEnum.userShippingAddressId.getParamName(),userAddressId.toString(),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[defaultUserAddress] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("设置默认用户地址接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject getAddressByPhone(Integer userId, String phone) throws Exception {
		ApiUrl apiUrl = this.buildMallApiBaseUrl("MALL_ORDER_ADDRESS_LIST");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								ApiUrlParamEnum.phone.getParamName(), phone,
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[getAddressByPhone] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取用户送货地址接口异常！");
		}
		return result;
	}
}